package whu.cn.whushare.ui.main.known;

import whu.cn.whushare.R;
import whu.cn.whushare.bean.User;
import whu.cn.whushare.common.Constants;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.BaseActivity;
import whu.cn.whushare.ui.common.LoadingHelper;
import whu.cn.whushare.ui.main.known.adapter.SearchUserAdapter;
import whu.cn.whushare.util.SetOnClickUtil;
import whu.cn.whushare.util.Utils;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;

import com.android.volley.VolleyError;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

@ViewMapping(id = R.layout.activity_invite_answer)          //获取activity_invite_answer布局文件
public class InviteAnswerActivity extends BaseActivity {
	@ViewMapping(id = R.id.refresh_list)                    //获取刷新列表
	private PullToRefreshListView mRefreshListView;

	private LoadingHelper mLoadingHelper;
	private int mCurPage = 1;
	private String mQuery = "";
	private List<User> mUsers = new ArrayList<>();
	private String mQuestionId;
	private SearchUserAdapter mAdapter;

    //获取跳转到当前activity的intent信息，向intent中添加问题id
	public static Intent getStartIntent(Context context, String questionId) {
		Intent intent = new Intent(context, InviteAnswerActivity.class);
		intent.putExtra(Constants.INTENT_EXTRA_QUESTION_ID, questionId);
		return intent;
	}

	@Override
    //activity加载时调用该方法，主要完成初始化操作
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getIntent() != null) {
			mQuestionId = getIntent().getStringExtra(Constants.INTENT_EXTRA_QUESTION_ID);
		}
		initView();
	}

    /**
     * 完成页面初始化操作
     */
	private void initView() {
		View root = ViewMappingUtil.mapView(this, this);
		getTopBar(root);
		SetOnClickUtil.registerOnClick(this);

		mLoadingHelper = new LoadingHelper(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				requestInvite(mCurPage);
			}
		});
		mLoadingHelper.onCreateView(LayoutInflater.from(this), mRefreshListView);

        //设置顶部菜单条
		mTopBar.searchLayout.setVisibility(View.VISIBLE);
		mTopBar.searchTxt.setText(R.string.invite);
		mTopBar.searchTxt.setOnClickListener(this);
		mTopBar.searchView.setOnClickListener(this);

		mAdapter = new SearchUserAdapter(mUsers, this);
		mRefreshListView.setAdapter(mAdapter);
		mRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);     //设置刷新模式

		mRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if (mTotal <= mUsers.size()) {
					Utils.setRefreshLabelToLast(InviteAnswerActivity.this, mRefreshListView);
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							mRefreshListView.onRefreshComplete();
						}
					}, 500);
				} else {
					requestInvite(mCurPage + 1);
				}
			}
		});

		mRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				User user = mAdapter.getItem(position - 1);
				saveInvite(user.getId());
			}
		});
	}

    //请求邀请他人回答问题
	private void requestInvite(int page) {
		mLoadingHelper.showLoadingView(false);
		Downloader.getInstance(this).searchUser(mQuery, page, 20, this, page);
	}

    //保存邀请信息
	private void saveInvite(String uid) {
		Downloader.getInstance(this).saveInvite(mQuestionId, uid, this, null);
	}

	@Override
    /**
     * 网络请求成功时调用该函数
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj) {
		super.onSuccess(type, response, obj);
		switch (type) {
		case SEARCH_USER:
			mRefreshListView.onRefreshComplete();
			mLoadingHelper.showContentView();
			if (response != null) {
				mCurPage = (int) obj;
				updateViews((List<User>) response);
			}
			break;
		case INVITE:
			toast(msg);
			finish();
			break;
		}
	}

	@Override
    /**
     * 网络请求失败时调用该函数，
     * 当网络请求类型为“评论”时，显示重试页面
     * 当网络请求类型为“添加评论”时，进行提示
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public void onFail(DownloadParams.PARSING_TYPE type, VolleyError error) {
		super.onFail(type, error);
		switch (type) {
		case SEARCH_USER:
			mRefreshListView.onRefreshComplete();
			if (mCurPage == 1) {
				mLoadingHelper.showRetryView();
			} else {
				mLoadingHelper.showContentView();
			}
			break;
		case INVITE:
			finish();
		}

		toast(msg);
	}

	private void updateViews(List<User> users) {
		if (mCurPage == 1) {
			mUsers.clear();
			Utils.resetRefreshLabel(this, mRefreshListView);    //重置刷新标志
		}

		mUsers.addAll(users);
	}

	@Override
    /**
     * 方法名：onClick(View v)
     * 功 能：根据发生点击事件的控件不同处理不同的点击事件
     * 参 数：@param v - 发生点击事件的控件
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
	public void onClick(View v) {
		super.onClick(v);
		int id = v.getId();
		switch (id) {
		case R.id.searchTxt:
			mQuery = mTopBar.searchView.getQuery().toString();
			if (TextUtils.isEmpty(mQuery)) {
				toast(R.string.no_query);
			} else {
				requestInvite(1);
			}
			break;
		default:
			break;
		}
	}
}
